package com.rivues.module.platform.web.handler;

import java.beans.PropertyDescriptor;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.solr.common.util.NamedList;
import org.apache.solr.common.util.SimpleOrderedMap;
import org.apache.solr.core.SolrCore;
import org.apache.solr.handler.PingRequestHandler;
import org.apache.solr.handler.RequestHandlerBase;
import org.apache.solr.request.SolrQueryRequest;
import org.apache.solr.response.SolrQueryResponse;
import org.apache.solr.util.plugin.SolrCoreAware;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.rivues.core.RivuDataContext;
import com.rivues.util.service.data.RequestStaticisBean;
import com.rivues.util.service.monitor.BusinessService;

public class SystemAPIHandler extends RequestHandlerBase implements
		SolrCoreAware {
	public static Logger log = LoggerFactory.getLogger(PingRequestHandler.class);

	@Override
	public void inform(SolrCore core) {

	}

	@Override
	public void handleRequestBody(SolrQueryRequest req, SolrQueryResponse rsp)
			throws Exception {
		org.apache.solr.common.params.SolrParams params = req.getParams();
		String serviceName = params.get("name") ;
		rsp.add("time", System.currentTimeMillis()) ;
		if(serviceName!=null){
	    	if(RivuDataContext.getStaticServiceMap().get(serviceName)==null){
	    		RivuDataContext.getStaticServiceMap().put(serviceName, new RequestStaticisBean(serviceName));
	    	}
	    	RequestStaticisBean staticisBean = RivuDataContext.getStaticServiceMap().get(serviceName) ;
	    	PropertyDescriptor[] properties = org.springframework.beans.BeanUtils.getPropertyDescriptors(staticisBean.getClass()) ;
	    	NamedList<String> namedList = new SimpleOrderedMap<String>() ;
	    	rsp.add("statistics", namedList) ;
	    	for(PropertyDescriptor property : properties){
	    		namedList.add(property.getName(), BeanUtils.getProperty(staticisBean, property.getName())) ;
	    	}
		}else{
			new PingRequestHandler().handleRequest(req, rsp) ;
		}
	}

	@Override
	  public String getDescription() {
	    return "Reports application health to a load-balancer";
	  }

	  @Override
	  public String getSource() {
	    return "$URL: https://svn.apache.org/repos/asf/lucene/dev/branches/lucene_solr_4_8/solr/core/src/java/org/apache/solr/handler/PingRequestHandler.java $";
	  }
}
